<?php


namespace app\sys\model;


use app\admin\model\Duty;
use think\Model;

class Role extends Model
{
    protected $autoWriteTimestamp = true;
    /**
     * 角色列表
     * @return array
     */
    public static function list():array
    {
        $resQ = Duty::alias("id")
            ->field("id.id,id.name as duty_name,ifnull(r.fun_name,'') as fun_name_all,sum(if(is.id > 0,1,0)) as duty_num")
            ->leftJoin("ic_role r","r.duty_id = id.id")
            ->leftJoin("ic_staff is","is.duty_id = id.id");

       $res = Duty::getQueryByDataPermId($resQ);
       $res =  $res->group("id.id")->select();

        $resCQ = Duty::alias("d")
            ->leftJoin("ic_staff is","is.duty_id = d.id");

        $resC = Duty::getQueryByDataPermId($resCQ);
        $resC = $resC->group("d.id")->count();

        return listDate($res,$resC);
    }

    /**
     * 角色权限
     * @param $dutyId
     * @param $arr
     * @return string
     */
    public static function RoleSave($dutyId,$arr):string
    {
        foreach ($arr as $k => $v){
            $funId[] = $v["fun_id"];
        }
        if(empty($funId)) return "功能id不能为空~";
        $funIdArr = implode($funId,",");
        $funName = Fun::where("id","in",$funId)->column("method_name");
        $funNameArr = implode($funName,",");
        $roleModel = Role::where("duty_id",$dutyId)->find();
        if($roleModel&&!isset($v["status"])){
            $roleData = ["fun_id"=>$funIdArr,"fun_name"=>$funNameArr];
            $roleModel->save($roleData);
        }elseif(!isset($v["status"])){
            $roleData = ["duty_id"=>$dutyId,"fun_id"=>$funIdArr,"fun_name"=>$funNameArr];
            Role::create($roleData);
        }
        // 功能权限
        if(!isset($v["status"])) {
            RoleLog::where("duty_id", $dutyId)->delete();
        }

        foreach ($arr as $v){
            if(isset($v["status"])){
                // 数据权限
                $status = isset($v["status"]) ? $v["status"] : 0;
                RoleLog::where("duty_id",$dutyId)->where("fun_id",$v["fun_id"])->data(["data_type"=>$status])->update();
            }else{
                // 功能权限
                $log = ["duty_id"=>$dutyId,"fun_id"=>$v["fun_id"]];
                RoleLog::create($log);
            }
        }
        return "";
    }
}